package com.hxgis.oc.controller;

import com.hxgis.oc.product.LiveProduct;
import com.hxgis.oc.util.ds.FileRecord;
import com.hxgis.oc.product.base.ProductFactory;
import com.hxgis.oc.product.base.ProductFactoryManager;
import com.hxgis.oc.util.ResponseHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/product")
public class ProductController {

    @GetMapping("/getFile")
    public ResponseEntity<Object> getFile(String dataSet,String product,String fileName,Long fid) throws IOException {
        HttpHeaders headers = null;
        byte[] res = null;
        File file = null;

        if((fileName != null || fid != null) && product != null){
            ProductFactory factory = ProductFactoryManager.getFactory(product);
            if(factory != null){
                if(fileName != null){
                    file = factory.getFile(dataSet,fileName);
                }else {
                    file = factory.getFile(dataSet,fid);
                }
                if(file == null && fid != null) {
                    file = LiveProduct.getFile(dataSet,fid,product);
                }
            }

            if(file != null && file.exists())
            {
                BufferedInputStream bf = new BufferedInputStream(Files.newInputStream(file.toPath()));
                res = new byte[bf.available()];
                bf.read(res);
                bf.close();
            }
        }

        if(res!=null)
        {
            headers = ResponseHelper.createFileHeader(file.getName(),res.length);
        }

        return new ResponseEntity<>(res, headers, res == null ? HttpStatus.NOT_FOUND : HttpStatus.OK);
    }

    @GetMapping("/getFileList")
    public List<FileRecord> getFileList(String dataSet,String product,Long startTime,Long endTime) {
        List<FileRecord> list = null;
        if( dataSet != null && product != null){
            ProductFactory factory = ProductFactoryManager.getFactory(product);
            if(factory != null){
                list = factory.getFileList(dataSet,startTime,endTime);
            }
        }
        return list;
    }
}
